#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define SERVER_PORT 8080
#define MAX_BUF_SIZE 100
#define FIFO "/tmp/datafifo"

int write_all(int fd, void *buf, int n)
{
        int nleft,nbytes;
        char *ptr;
        nleft=n;
        ptr=buf;
        for(;nleft>0;){
                nbytes=write(fd,ptr,nleft);
                if(nbytes<=0){
                        if(errno==EINTR) nbytes=0;
                        else return(-1);
                }
                nleft-=nbytes;
                ptr+=nbytes;
        }
        return(n);
}


void cli_requ(int sockfd){
	char inbuf[MAX_BUF_SIZE];
	int n;
        int fifo_fd;
        int nread;

        //判断fifo管道是否已经存在，若未创建则以相应的权限创建
        if(access(FIFO,F_OK)==-1)
        {
		if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
                {
			printf("cannot create fifoserver\n");
                        exit(-1);
                }
        }
       	fifo_fd=open(FIFO,O_RDONLY,0);
	if(fifo_fd==-1)
        {
        	perror("open FIFO error\n");
                exit(1);
        }
        
	while(1){
	        memset(inbuf,'\0',sizeof(inbuf));  //初始化缓冲区
        	if((nread=read(fifo_fd,inbuf,100))==-1) //读取管道文件
	        {
        	        if(errno==EAGAIN)
                	{
                        	printf("no data yet\n");
	                        break;
        	        }
	        }

        	if(nread>0) //如果读取到的数据长度大于0，发送到服务器
	        {
        	      	//读到数据，在inbuf中                   
              		write_all(sockfd,inbuf,nread);
		}
		sleep(1);
	}
        pause();
        unlink(FIFO);//delete FIFO
}
void main(int argc, char* argv[])
{
	int sockfd;
	struct sockaddr_in servaddr;
	if(argc<2){
		fprintf(stderr,"usage:client<IPaddress>\n");
		exit(1);
	}
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0){
		fprintf(stderr,"socked error\n");
		exit(1);
	}
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(SERVER_PORT);
	if(inet_aton(argv[1],&servaddr.sin_addr)==0){
		fprintf(stderr,"Inet_aton error\n");
		exit(1);
	}
	if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){
		fprintf(stderr,"connect error:%s\n",strerror(errno));
		exit(1);
	}
	cli_requ(sockfd);
	close(sockfd);
}
